package com.framework.buss.bridge.service.impl;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.framework.buss.bridge.model.WordByte;
import com.framework.buss.bridge.mapper.WordByteMapper;
import com.framework.buss.bridge.service.IWordByteService;
import com.google.common.io.ByteStreams;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

@Log4j2
@Service
public class WordByteServiceImpl implements IWordByteService {
    @Autowired
    private WordByteMapper wordByteMapper;

    @Override
    public void saveWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = null;
        InputStream ins = null;
        HttpURLConnection connection = null;
        try {
            writer = response.getWriter();
            Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
            String body = scanner.hasNext() ? scanner.next() : "";
            JSONObject jsonObj = JSONObject.parseObject(body);
            log.info("在线编辑器回调参数：{}", jsonObj);
            String fileName = request.getParameter("name");
            String fileId = request.getParameter("id");
            if (StringUtils.isBlank(fileName)) {
                fileName = "模板文件.docx";
            }

            String downUrl = (String) jsonObj.get("url"); //保存变更后文件
            if ((Integer) jsonObj.get("status") == 6) {
                URL url = new URL(downUrl);
                connection = (HttpURLConnection) url.openConnection();
                ins = connection.getInputStream();
                WordByte wordByte = new WordByte();
                wordByte.setLength(connection.getContentLength());
                wordByte.setFileId(fileId);
                wordByte.setFileName(fileName);
                byte[] byteArray = ByteStreams.toByteArray(ins);
                wordByte.setData(byteArray);
                // 删除旧文件
                QueryWrapper wrapper = new QueryWrapper<>();
                wrapper.eq("file_id", fileId);
                wordByteMapper.delete(wrapper);

                // 保存新文件
                wordByteMapper.insert(wordByte);
            }
            writer.write("{\"error\":0}");
        } catch (Exception e) {
            if (null != writer) {
                writer.write("{\"error\":1}");
            }
        } finally {
            if (null != ins) {
                ins.close();
            }
            if (null != connection) {
                connection.disconnect();
            }
            if (null != writer) {
                writer.close();
            }
        }
    }

    @Override
    public void loadWord(String fileId, HttpServletResponse response) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("file_id", fileId);
        WordByte wordByte = wordByteMapper.selectOne(wrapper);
        if (null == wordByte) {
            // 没有的话，默认取第一个
            wordByte = wordByteMapper.selectById("0");
        }
        String fileName = wordByte.getFileName();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; " + "filename*=UTF-8''" + fileName);
        response.setCharacterEncoding("UTF-8");response.setContentType("application/octet-stream");
        //注意类型一定要是octet-stream
        byte[] bytes = wordByte.getData();
        response.setContentLength(wordByte.getLength());
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (null != os) {
                IoUtil.close(os);
            }
        }
    }

    @Override
    public void readFile(String temp, String bridgeId) {
        File file = new File(temp);
        try (
                InputStream is = new FileInputStream(file);
        ) {
            WordByte wordByte = new WordByte();
            wordByte.setLength(is.available());
            wordByte.setFileId(bridgeId);
            wordByte.setFileName(bridgeId.concat(".docx"));
            byte[] byteArray = ByteStreams.toByteArray(is);
            wordByte.setData(byteArray);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        file.delete();
    }
}
